import { defineStore } from 'pinia'
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import * as homeApi from '@/api/home'
import type { Post } from '@/api/post'
import type { Announcement, ActiveUser } from '@/api/home'

export const useHomeStore = defineStore('home', () => {
  const hotPosts = ref<Post[]>([])
  const latestPosts = ref<Post[]>([])
  const announcements = ref<Announcement[]>([])
  const activeUsers = ref<ActiveUser[]>([])
  const loading = ref(false)

  // 获取热门帖子
  const fetchHotPosts = async () => {
    try {
      loading.value = true
      const res = await homeApi.getHotPosts()
      if (res.code === 200) {
        hotPosts.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取热门帖子失败')
    } finally {
      loading.value = false
    }
  }

  // 获取最新帖子
  const fetchLatestPosts = async () => {
    try {
      loading.value = true
      const res = await homeApi.getLatestPosts()
      if (res.code === 200) {
        latestPosts.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取最新帖子失败')
    } finally {
      loading.value = false
    }
  }

  // 获取公告列表
  const fetchAnnouncements = async () => {
    try {
      loading.value = true
      const res = await homeApi.getAnnouncements()
      if (res.code === 200) {
        announcements.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取公告列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取活跃用户
  const fetchActiveUsers = async () => {
    try {
      loading.value = true
      const res = await homeApi.getActiveUsers()
      if (res.code === 200) {
        activeUsers.value = res.data
      }
    } catch (error: any) {
      message.error(error.message || '获取活跃用户失败')
    } finally {
      loading.value = false
    }
  }

  // 初始化首页数据
  const initHomeData = async () => {
    loading.value = true
    try {
      await Promise.all([
        fetchHotPosts(),
        fetchLatestPosts(),
        fetchAnnouncements(),
        fetchActiveUsers()
      ])
    } finally {
      loading.value = false
    }
  }

  return {
    hotPosts,
    latestPosts,
    announcements,
    activeUsers,
    loading,
    fetchHotPosts,
    fetchLatestPosts,
    fetchAnnouncements,
    fetchActiveUsers,
    initHomeData
  }
}) 